﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.VoiceCommands;
using Windows.Foundation;
using Windows.Storage;
using Windows.System.Profile;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http.Headers;
using ArticleandSiteData;
using Microsoft.ApplicationInsights;
using ModelClassLibrary;
using HttpMethod = Windows.Web.Http.HttpMethod;
using HttpRequestMessage = Windows.Web.Http.HttpRequestMessage;

//using Microsoft.Data.Entity;

namespace SplitViewOptions
{
    /// <summary>
    ///     Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
     public   static bool isgoingback = false;
        /// <summary>
        ///     Initializes the singleton application object.  This is the first line of authored code
        ///     executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        /// pu
        /// s
        /// 
        public App()
        {
            WindowsAppInitializer.InitializeAsync(
                WindowsCollectors.Metadata |
                WindowsCollectors.Session);
            InitializeComponent();
            Suspending += OnSuspending;
            if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
            {
                Homesiteurl = "http://baidu.com/";
                Ismobile = true;

                ApplicationView.PreferredLaunchViewSize = new Size(480, 800);
                ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
                // ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(768, 1365));
            }
            if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile")
            {
                Homesiteurl = "https://m.baidu.com/";
                Ismobile = true;
            }
            try
            {
                SetorginDesktopSites();
                //using (var db = new BloggingContext())
                //{
                //    db.Database.Migrate();
                //}
                // setorginDesktopSites();
            }
            catch (Exception ex)
            {
            }

            UnhandledException += App_UnhandledException;
        }

        private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            string str = e.Message + "\r\n" +
                         e.Exception.Source + "\r\n" +
                         e.Exception.StackTrace + "\r\n" +
                         e.Exception.Message + "\r\n";
                         //+
                         //e.Exception.InnerException.Source+"\r\n"+
                         //e.Exception.InnerException.Message;

            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("unhand.txt");
            await FileIO.WriteTextAsync(file, str);
        }

        //todo:放配置  ——林德熙
        public static string GetallsiteUrl
        {
            set;
            get;
        } = "https://api.bmob.cn/1/classes/test";

        public static string RegisterUrl
        {
            set;
            get;
        } = "https://api.bmob.cn/1/classes/users";

        /// <summary>
        /// 收藏api
        /// </summary>
        public static string UserArticleorSiteUrl
        {
            set;
            get;
        } = "https://api.bmob.cn/1/classes/userarticleorsite";

        /// <summary>
        /// app 内分享api
        /// </summary>
        public static string ShareSiteorArticle
        {
            set;
            get;
        } = "https://api.bmob.cn/1/classes/sharesiteorarticle";

        public static string Desktopsites
        {
            set;
            get;
        } = "https://api.bmob.cn/1/classes/UserdesktopSite";

        public static string Oneuserdesktopsites
        {
            set;
            get;
        } = "https://api.bmob.cn/1/classes/UserdesktopSite";

        public static string Loginsiteurl
        {
            set;
            get;
        } = "https://api.bmob.cn/1/login";

        public static string Homesiteurl
        {
            set;
            get;
        } = "http://codehi.github.io/";

        public static List<string> Picurllist
        {
            set;
            get;
        } = null;

        public static bool Isdownloadstirngmode
        {
            set;
            get;
        } = false;

        public static string Recommendsiteurl
        {
            set;
            get;
        } = "http://files.cnblogs.com/files/gisbeginner/recommendwebsite.xml";

        public static LoginReturnUser Loginuser
        {
            set;
            get;
        }

        public static string Bmobname
        {
            set;
            get;
        } = "";

        public static string Bmobrestapikeyname
        {
            set;
            get;
        } = "";

        public static string Curruntprovince
        {
            set;
            get;
        } = "";

        public static string Addurlstr
        {
            set;
            get;
        } = "";

        public static string Objectid
        {
            set;
            get;
        } = "";

        public static string Addnamestr
        {
            set;
            get;
        } = "";

        public static string Setwebbdoybakcgroudstr
        {
            set;
            get;
        } = " document.getElementById(\"body\").style.background = \"black\";document.style.color=\"Red\";";

        public static Frame Mainframe
        {
            set;
            get;
        } = null;

        public static Grid Picnel
        {
            set;
            get;
        } = null;

        public static Grid Menutoatlpicnel
        {
            set;
            get;
        }

        public static Grid Tooltipgrid
        {
            set;
            get;
        } = null;

        public static RelativePanel Mainmenugrid
        {
            set;
            get;
        }

        public static string Bmobapplicationkeyname
        {
            set;
            get;
        } = "";

        public static string Htmlstringcontent
        {
            set;
            get;
        } = "";

        public static string Applicationid
        {
            set;
            get;
        } = "1f570053c58338812a8970abbbaaa623";

        public static string Restkeyid
        {
            set;
            get;
        } = "d803ea3828a42eba94ecbc9ea47d435a";

        public static Uri Currenturl
        {
            set;
            get;
        }

        public static bool Ismobile
        {
            set;
            get;
        } = true;

        public static bool Isfully
        {
            set;
            get;
        } = false;

        public static bool Issecondwebviewmanipulated
        {
            set;
            get;
        } = false;

        public static bool Ischangeuseragnet
        {
            set;
            get;
        }

        public static bool Isbackgroundmode
        {
            set;
            get;
        } = false;

        public static bool Isnightmode
        {
            set;
            get;
        } = false;

        public static bool Iswithoutpicmode
        {
            set;
            get;
        } = false;

        public static bool Readmode
        {
            set;
            get;
        } = false;

        public static bool Isunlocksmode
        {
            set;
            get;
        } = false;

        public static WebView Webview
        {
            set;
            get;
        } = null;

        public static WebView Secondwebview
        {
            set;
            get;
        } = null;

        public static ObservableCollection<Info> Itemssites
        {
            set;
            get;
        } = null;

        public static AutoSuggestBox Titlebox
        {
            set;
            get;
        } = null;

        public static Dictionary<string, string> Desktopsitesdic
        {
            set;
            get;
        } = new Dictionary<string, string>();

        public static async Task Addoruodatedesktopsites()
        {
            try
            {
                if (Loginuser != null)
                {
                    var desktopone = await BmobWebsiteData.GetAllwebsitesinfoone<DesktopSitesResult>(Desktopsites);
                    foreach (var a in desktopone.results)
                    {
                        if (a.userid == Loginuser.objectId)
                        {
                            Objectid = a.objectId;
                            break;
                        }
                    }

                    var userid = Loginuser.objectId;
                    var username = Loginuser.username;
                    var sitesurls = string.Empty;
                    var sitenames = string.Empty;
                    if (string.IsNullOrEmpty(Objectid))
                    {
                        foreach (var a in GetDesktopsites())
                        {
                            sitesurls = a.dataurl + "," + sitesurls;
                            sitenames = a.text + "," + sitenames;
                        }
                        Debug.WriteLine("ADD NEW DESK");
                        var jsonstr = "{" + "\"" + "userid" + "\"" + ":" + "\"" + userid + "\"" + "," + "\"" +
                                      "usersites" + "\"" + ":" + "\"" + sitesurls + "\"" + "," + "\"" + "usersitesname" +
                                      "\"" + ":" + "\"" + sitenames + "\"" + "}";
                        var content = new StringContent(jsonstr);
                        var oneHttpResponseMessage =
                            await BmobWebsiteData.AddOne<HttpResponseMessage>(Desktopsites, jsonstr);
                        if (oneHttpResponseMessage.StatusCode == HttpStatusCode.Created)
                        {
                            //MessageDialog one = new MessageDialog("成功");
                            //await one.ShowAsync();
                        }
                    }
                    else
                    {
                        var items = GetDesktopsites();
                        var tempurl = string.Empty;
                        var tempname = string.Empty;
                        foreach (var a in items)
                        {
                            tempurl = a.dataurl + "," + tempurl;
                            tempname = a.text + "," + tempname;
                        }
                        Debug.WriteLine(tempname);

                        Debug.WriteLine("PUT CHANGE OBJECT");
                        var putjsonstr = "{" + "\"" + "userid" + "\"" + ":" + "\"" + Loginuser.objectId + "\"" + "," +
                                         "\"" + "usersites" + "\"" + ":" + "\"" + tempurl + "\"" + "," + "\"" +
                                         "usersitesname" + "\"" + ":" + "\"" + tempname + "\"" + "}";
                        var putcontent = new StringContent(putjsonstr);
                        var putoneHttpResponseMessage =
                            await
                                BmobWebsiteData.Putjson<HttpResponseMessage>(Desktopsites + "/" + Objectid, putjsonstr);
                        if (putoneHttpResponseMessage.StatusCode == HttpStatusCode.OK)
                        {
                            // MessageDialog one = new MessageDialog("更新成功");
                            // await one.ShowAsync();
                        }
                    }
                }
            }
            catch (Exception EX)
            {
            }
        }

        public static ObservableCollection<Info> GetDesktopsites()
        {
            var resultlist = new ObservableCollection<Info>();
            foreach (var a in _localSettings.Values.Keys)
            {
                if (a.StartsWith("http") || a.StartsWith("www"))
                {
                    var oneinfo = new Info();
                    oneinfo.dataurl = a;
                    oneinfo.text = _localSettings.Values[a].ToString();
                    resultlist.Add(oneinfo);
                }
            }
            return resultlist;
        }

        public static bool AddDesktopsites(string url, string name)
        {
            var result = true;
            if (!_localSettings.Values.Keys.Contains(url))
            {
                _localSettings.Values[url] = name;
            }
            return result;
        }

        /// <summary>
        ///     Invoked when the application is launched normally by the end user.  Other entry points
        ///     will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            //CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

#if DEBUG
            if (Debugger.IsAttached)
            {
                // this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            //InsertVoiceCommands();
            var rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                    if (!_localSettings.Values.Keys.Contains("currenturl"))
                    {
                        Uri url = null;
                        url = _localSettings.Values["currenturl"] as Uri;
                        Currenturl = url;
                        Debug.WriteLine(Currenturl?.AbsoluteUri + "OnLaunched");
                        rootFrame.Navigate(typeof(HomePage));
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (_localSettings.Values["objectId"] != null)
            {
                var user = new LoginReturnUser();
                user.objectId = _localSettings.Values["objectId"].ToString();
                user.username = _localSettings.Values["username"].ToString();
                user.updatedAt = _localSettings.Values["updatedAt"].ToString();
                user.sessionToken = _localSettings.Values["sessionToken"].ToString();
                user.createdAt = _localSettings.Values["createdAt"].ToString();
                Loginuser = user;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
            }
            // await   InstallVoiceCommand();
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
                AppViewBackButtonVisibility.Visible;
            // Ensure the current window is active
            Window.Current.Activate();
        }

        public static void Navigatemobilemode(WebView homewebview, Uri url)
        {
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
            // var add = "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; WebView/3.0; Microsoft; Virtual) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10586 sample/1.0";
            //  string add = "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
            // string add = "Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10";
            //  string add = "Mozilla/5.0 (Linux; U; Android 2.2; en-gb; GT-P1000 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
            //string add= "http://whatsmyuseragent.com/"
            var add =
                "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25";
            // httpRequestMessage.Headers.Add("User-Agent", add);
            httpRequestMessage.Headers.UserAgent.Add(new HttpProductInfoHeaderValue(add));
            Ischangeuseragnet = false;
            homewebview.NavigateWithHttpRequestMessage(httpRequestMessage);
        }

        public static async Task showmessage(string str)
        {
            Tooltipgrid.Visibility = Visibility.Visible;
            var tb = Tooltipgrid.FindName("tooltiptb") as TextBlock;
            tb.Text = str;
            await Task.Delay(TimeSpan.FromSeconds(3));
            Tooltipgrid.Visibility = Visibility.Collapsed;
            //if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
            //{

            //    App.tooltipgrid.Visibility = Visibility.Visible;
            //    TextBlock tb= App.tooltipgrid.FindName("tooltiptb") as TextBlock;
            //    tb.Text = str;
            //    await Task.Delay(TimeSpan.FromSeconds(3));
            //    App.tooltipgrid.Visibility = Visibility.Collapsed;
            //    //ToolTip toolTip = new ToolTip() { FontSize=15};
            //    //toolTip.Content = str;
            //    //ToolTipService.SetToolTip(ul, toolTip);
            //    //MessageDialog one = new MessageDialog(str);
            //    //await one.ShowAsync();
            //    return ;
            //}
            //if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile")
            //{
            //    var statusbar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
            //    statusbar.ProgressIndicator.Text = str;
            //    statusbar.BackgroundColor = Windows.UI.Colors.Green;
            //    statusbar.BackgroundOpacity = 1;
            //    statusbar.ForegroundColor = Windows.UI.Colors.Red;
            //    await statusbar.ProgressIndicator.ShowAsync();
            //    return;
            //}
        }

        public static async Task showmessage(string str, int i)
        {
            Tooltipgrid.Visibility = Visibility.Visible;
            var tb = Tooltipgrid.FindName("tooltiptb") as TextBlock;
            tb.Text = str;
            await Task.Delay(TimeSpan.FromMilliseconds(i));
            Tooltipgrid.Visibility = Visibility.Collapsed;
            //if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
            //{

            //    App.tooltipgrid.Visibility = Visibility.Visible;
            //    TextBlock tb= App.tooltipgrid.FindName("tooltiptb") as TextBlock;
            //    tb.Text = str;
            //    await Task.Delay(TimeSpan.FromSeconds(3));
            //    App.tooltipgrid.Visibility = Visibility.Collapsed;
            //    //ToolTip toolTip = new ToolTip() { FontSize=15};
            //    //toolTip.Content = str;
            //    //ToolTipService.SetToolTip(ul, toolTip);
            //    //MessageDialog one = new MessageDialog(str);
            //    //await one.ShowAsync();
            //    return ;
            //}
            //if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile")
            //{
            //    var statusbar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
            //    statusbar.ProgressIndicator.Text = str;
            //    statusbar.BackgroundColor = Windows.UI.Colors.Green;
            //    statusbar.BackgroundOpacity = 1;
            //    statusbar.ForegroundColor = Windows.UI.Colors.Red;
            //    await statusbar.ProgressIndicator.ShowAsync();
            //    return;
            //}
        }

        protected override void OnActivated(IActivatedEventArgs args)
        {
            base.OnActivated(args);
            // 如果程序不是因为语音命令而激活的，就不处理
            //if (args.Kind != ActivationKind.VoiceCommand) return;

            //将参数转为语音指令事件对象
            var vcargs = (VoiceCommandActivatedEventArgs)args;
            // 分析被识别的命令
            var res = vcargs.Result;
            // 获取被识别的命令的名字
            var cmdName = res.RulePath[0];
            Type navType = null;
            string propertie = null;
            //判断用户使用的是哪种语音指令
            switch (cmdName)
            {
                case "OpenDuocaiBroswer":
                    navType = typeof(MainPage);
                    break;
                case "OpenBroswer":
                    navType = typeof(MainPage);
                    //获取语音指令的参数
                    //  propertie = res.SemanticInterpretation.Properties["City"][0];
                    break;
                case "opensite":
                    navType = typeof(MainPage);
                    //获取语音指令的参数
                    propertie = res.SemanticInterpretation.Properties["websites"][0];
                    var stri = string.Empty;
                    if (propertie == "百度")
                    {
                        stri = "https://www.baidu.com/";
                    }
                    if (propertie == "腾讯")
                    {
                        stri = "http://qq.com/";
                    }
                    if (propertie == "天涯")
                    {
                        stri = "http://tianya.cn/";
                    }
                    if (propertie == "网易")
                    {
                        stri = "http://163.com/";
                    }
                    if (propertie == "凤凰网")
                    {
                        stri = "http://ifeng.com/";
                    }
                    if (propertie == "搜狐")
                    {
                        stri = "http://sohu.com/";
                    }
                    Currenturl = new Uri(stri, UriKind.RelativeOrAbsolute);
                    break;
                case "NavToPage":
                    //获取语音指令的参数
                    propertie = res.SemanticInterpretation.Properties["Destination"][0];

                    //根据 propertie 参数决定跳转到指定界面，这里就不判断了
                    navType = typeof(MainPage);
                    break;
            }
            //获取页面引用
            var root = Window.Current.Content as Frame;
            if (root == null)
            {
                root = new Frame();
                Window.Current.Content = root;
            }
            root.Navigate(navType, propertie);

            // 确保当前窗口处于活动状态
            Window.Current.Activate();
        }

        protected override void OnFileActivated(FileActivatedEventArgs args)
        {
            // TODO: Handle file activation
            var frame = CreateRootFrame();
            if (frame.Content == null)
            {
                if (!frame.Navigate(typeof(MainPage), args))
                {
                }
            }
            //我是sb  ——林德熙
            if (args.Files.Count == 0)
            {
                return;
            }
            // The number of files received is args.Files.Size
            // The name of the first file is args.Files[0].Name
            var filepath = args.Files[0].Path;
            Debug.WriteLine(filepath);

            ////小说
            //var file = args.Files[0] as StorageFile;
            //if (file != null && file.FileType == ".txt")
            //{
            //    frame.Navigate(typeof(lindexi.uwp.Clenjw.View.Preface), file);
            //    return;
            //}

            var name = args.Files[0].Name;
            if (name.EndsWith("html") || name.EndsWith("htm") || name.EndsWith("cshtml"))
            {
                frame.Navigate(typeof(MainPage), args);
            }
            else
            {
                frame.Navigate(typeof(MainPage), args);
            }
            Window.Current.Activate();
        }

        private void SetorginDesktopSites()
        {
            if (!_localSettings.Values.Keys.Contains("http://m.weather.com.cn/"))
            {
                _localSettings.Values["http://m.weather.com.cn/"] = "天气";
            }
            if (!_localSettings.Values.Keys.Contains("https://m.baidu.com/"))
            {
                _localSettings.Values["https://m.baidu.com/"] = "百度";
            }
            if (!_localSettings.Values.Keys.Contains("http://info.3g.qq.com/"))
            {
                _localSettings.Values["http://info.3g.qq.com/"] = "腾讯";
            }
            if (!_localSettings.Values.Keys.Contains("http://3g.163.com/touch/"))
            {
                _localSettings.Values["http://3g.163.com/touch/"] = "网易";
            }
            if (!_localSettings.Values.Keys.Contains("http://m.sohu.com/"))
            {
                _localSettings.Values["http://m.sohu.com/"] = "搜狐";
            }
            if (!_localSettings.Values.Keys.Contains("http://m.tianya.cn/"))
            {
                _localSettings.Values["http://m.tianya.cn/"] = "天涯";
            }
            //if (!_localSettings.Values.Keys.Contains("https://m.hao123.com/"))
            //{
            //    _localSettings.Values["https://m.hao123.com/"] = "hao123";
            //}
            if (!_localSettings.Values.Keys.Contains("http://www.2345.com/?k862014631"))
            {
                _localSettings.Values["http://www.2345.com/?k862014631"] = "2345";
            }
            if (!_localSettings.Values.Keys.Contains("http://m.meituan.com/"))
            {
                _localSettings.Values["http://m.meituan.com/"] = "美团";
            }
            if (!_localSettings.Values.Keys.Contains("http://m.youku.com/"))
            {
                _localSettings.Values["http://m.youku.com/"] = "优酷";
            }
            if (!_localSettings.Values.Keys.Contains("http://m.taobao.com/"))
            {
                _localSettings.Values["http://m.taobao.com/"] = "淘宝";
            }
            if (!_localSettings.Values.Keys.Contains("http://m.zhihu.com/"))
            {
                _localSettings.Values["http://m.zhihu.com/"] = "知乎";
            }
            if (!_localSettings.Values.Keys.Contains("http://news.ruanfenquan.com/"))
            {
                _localSettings.Values["http://news.ruanfenquan.com/"] = "win10新闻";
            }
            if (!_localSettings.Values.Keys.Contains("http://bbs.ruanfenquan.com/"))
            {
                _localSettings.Values["http://bbs.ruanfenquan.com/"] = "软粉圈";
            }
            if (!_localSettings.Values.Keys.Contains("http://weibo.com/"))
            {
                _localSettings.Values["http://weibo.com/"] = "微博";
            }

            if (!_localSettings.Values.Keys.Contains("http://wap.ithome.com/"))
            {
                _localSettings.Values["http://wap.ithome.com/"] = "IT之家";
            }
            if (!_localSettings.Values.Keys.Contains("http://m.hexun.com/"))
            {
                _localSettings.Values["http://m.hexun.com/"] = "和讯";
            }
            if (!_localSettings.Values.Keys.Contains("http://m.toutiao.com/"))
            {
                _localSettings.Values["http://m.toutiao.com/"] = "头条";
            }
        }

        /// <summary>
        ///     Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        /// <summary>
        ///     Invoked when application execution is being suspended.  Application state is saved
        ///     without knowing whether the application will be terminated or resumed with the contents
        ///     of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            if (Mainframe.CurrentSourcePageType == typeof(HomePage))
            {
                //TODO: Save application state and stop any background activity
                if (!_localSettings.Values.Keys.Contains("currenturl"))
                {
                    _localSettings.Values["currenturl"] = Currenturl;
                }
            }
            deferral.Complete();
        }

        /// <summary>
        ///     注册语音指令
        /// </summary>
        private async Task InsertVoiceCommands()
        {
            await VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(
                await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///VoiceCommandsFile.xml")));
        }

        private async Task InstallVoiceCommand()
        {
            try

            {
                //user can stop VCD in settings

                //if (AppSettings.GetInstance().CortanaVCDEnableStatus == false)

                //    return;

                // Install the main VCD. Since there's no simple way to test that the VCD has been imported, or that it's your most recent

                // version, it's not unreasonable to do this upon app load.

                var vcdStorageFile = await Package.Current.InstalledLocation.GetFileAsync(@"VoiceCommandsFile.xml");

                await VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(vcdStorageFile);
            }

            catch (Exception ex)

            {
                Debug.WriteLine("Installing Voice Commands Failed: " + ex);
            }
        }

        private Frame CreateRootFrame()
        {
            var rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                // Set the default language
                //    rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
                rootFrame.NavigationFailed += OnNavigationFailed;

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            return rootFrame;
        }

        public static string nd =
            "var allElem = document.getElementsByTagName(\"*\");for (var i = 0; i<allElem.length; i++) {	var e = allElem[i]; e.style.color = \"lightblue\";e.style.backgroundColor = \"black\";e.style.backgroundImage = \"none\";}";

        private static readonly ApplicationDataContainer _localSettings =
            ApplicationData.Current.LocalSettings;
        public static int key = 0;

    }
}